extends CharacterBody2D

class_name Player

enum PlayerState { NORMAL, EXECUTE_FLIGHT }

var current_state = PlayerState.NORMAL       # 当前状态
var execute_target =null
var current_velocity: Vector2 = Vector2.ZERO
var acceleration: float = 1000.0
var deceleration: float = 100.0 
var target_position: Vector2 = Vector2.ZERO

var last_move=null
var speed_add = 20
var cur_speed = speed
var is_dashable =true

#关于节奏的参数
var is_beat:bool =false


@export var max_speed:int = 400
@export	var speed: int = 200
@export var execute_speed = 1000
@export var execute_distance = 50 
@export var aim_tolerance = 20 
@export var dash_distance = 10 

@onready var collision_shape = $CollisionShape2D
@onready var health_sta =$Health
@onready var weapon = $Weapon
@onready var collision=$CollisionShape2D
@onready var dash_timer=$dashTimer
@onready var tip=$ColorRect
@onready var idelplayer=$AnimationPlayer

func _physics_process(delta: float) -> void:
	player_move()
	player_flying(delta)
	if is_beat:
		tip.visible = true
	else:
		tip.visible = false
	
func _unhandled_input( event: InputEvent) -> void:
	#收到每次点击时发射
	if current_state != PlayerState.NORMAL:
		return
	if event.is_action_released("shoot"): 
		if is_beat:
			GlobalSignals.emit_signal("energy_add")
		weapon.shoot()
		
func handel_hit(cur_damage):
	if current_state != PlayerState.EXECUTE_FLIGHT:
		health_sta.cur_health -=cur_damage
		if health_sta <=0:
			queue_free()
	
func heal(amount: int):
	health_sta.cur_health += amount
	health_sta.cur_health = min(health_sta.cur_health, health_sta.max_health)  # 血量不超过最大值

func executing(enemy):
	execute_target = enemy
	current_state = PlayerState.EXECUTE_FLIGHT
	current_velocity = Vector2.ZERO

func finish_flying():
	current_state = PlayerState.NORMAL
	# 播放处决动画
	# 执行处决逻辑（如扣减敌人血量）
	execute_target.executed()
	execute_target =null;
	current_velocity = Vector2.ZERO
	# 停止飞行动画

func player_move():
	#移动方向控制aas
	if current_state == PlayerState.NORMAL:
		var movement_direction := Vector2.ZERO
		if Input.is_action_pressed("up"):
			movement_direction.y = -1
		if Input.is_action_pressed("down"):
			movement_direction.y = 1
		if Input.is_action_pressed("left"):
			movement_direction.x = -1
		if Input.is_action_pressed("right"):
			movement_direction.x = 1


	#归一化
		movement_direction = movement_direction.normalized()
		#移动
		if last_move == movement_direction:
			cur_speed = min(cur_speed + speed_add,max_speed)
		else:
			cur_speed = speed
		set_velocity(movement_direction * cur_speed)
		move_and_slide()
		last_move =movement_direction
	#角色面向鼠标方向
		look_at(get_global_mouse_position())
	#dash功能实现 todo:加效果
		if Input.is_action_pressed("dash") and is_beat:
			if last_move!=null and is_dashable:
				current_state = PlayerState.EXECUTE_FLIGHT
				set_velocity(last_move * execute_speed*dash_distance)
				move_and_slide()
				current_state = PlayerState.NORMAL
				is_dashable =false
				dash_timer.start()
	
func player_flying(delta):
	if current_state == PlayerState.EXECUTE_FLIGHT:
		
		target_position = execute_target.global_position
	
	# 计算当前位置到目标位置的向量
		var direction = target_position - global_position
		var distance = direction.length()
		var pixel_area = max(collision.shape.size.x,collision.shape.size.y)
		# 若已到达目标（误差小于x像素），停止飞行并执行处决
		if distance < pixel_area :
			global_position = target_position  # 精确对齐目标位置
			finish_flying()
			return
		
		# 计算目标速度（基于距离动态调整：加速→匀速→减速）
		var target_speed = execute_speed

		if distance > 200:  # 远距离加速
			target_speed = min(execute_speed, acceleration * delta)
		elif distance < 50:   # 近距离减速
			target_speed = max(0, execute_speed - deceleration * delta)
		else:                 # 中距离匀速
			target_speed = execute_speed
		# 计算速度方向（归一化后乘以目标速度）
		#var velocity = direction.normalized()
		var velocity = direction.normalized() * target_speed
		# 应用速度（使用物理引擎自动处理碰撞）d
		current_velocity = velocity
		move_and_collide(current_velocity)
	

#dashCD
func _on_dash_timer_timeout():
	is_dashable = true

func handle_beat_star():
	is_beat = true

func handle_beat_stop():
	is_beat = false
